#! _*_ coding: utf8 _*_
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import api_view

from news.models import News
from news.serializers import NewsSeri
from tools.err import RoingException


@api_view(['GET', 'POST'])
def news_list(request):
    params = request.GET
    page = params.get('page', 0)
    offset = params.get('offset', 0)
    limit = params.get('limit', 20)

    offset = int(offset)
    limit = int(limit)
    newses = News.objects.all().order_by('-create_date')[offset: offset + limit]
    return JsonResponse({'newses': NewsSeri(newses, many=True).data})


@api_view(['GET', 'POST'])
def add_news(request):
    link = request.data.get('link', None)
    if News.objects.filter(link=link):
        raise RoingException(message=u'该文章已经被收录', code=605)

    seri = NewsSeri(data=request.data)
    if not seri.is_valid():
        raise RoingException(message=u'添加资讯失败，请确定有正确的标题和摘要', code=604)
    news = seri.save()
    return JsonResponse(NewsSeri(news).data)
